<template>
    <el-dialog 
        :title="title" 
        :visible.sync="dialogVisible" 
        width="70%" 
        append-to-body
        @open="handleDialogOpen"
        @closed="handleDialogClose">
        <div class="map-container">
            <div class="map-search">
                <el-input
                    v-model="searchAddress"
                    placeholder="输入地址搜索"
                    @keyup.enter.native="searchLocation">
                    <el-button slot="append" icon="el-icon-search" @click="searchLocation">搜索</el-button>
                </el-input>
            </div>
            <div id="amap" class="map-content"></div>
        </div>
        <div class="selected-address" v-if="selectedAddress">
            <div class="address-info">
                <div class="info-item">
                    <span class="label">地址：</span>
                    <span class="value">{{ selectedAddress }}</span>
                </div>
                <div class="info-item" v-if="selectedPosition">
                    <span class="label">经度：</span>
                    <span class="value">{{ selectedPosition.lng }}</span>
                </div>
                <div class="info-item" v-if="selectedPosition">
                    <span class="label">纬度：</span>
                    <span class="value">{{ selectedPosition.lat }}</span>
                </div>
            </div>
        </div>
        <div slot="footer" class="dialog-footer">
            <el-button @click="handleCancel">取 消</el-button>
            <el-button type="primary" @click="handleConfirm">确 定</el-button>
        </div>
    </el-dialog>
</template>

<script>
import AMapLoader from '@amap/amap-jsapi-loader'

export default {
    name: 'AMapPicker',
    props: {
        visible: {
            type: Boolean,
            default: false
        },
        title: {
            type: String,
            default: '选择位置'
        },
        initialCenter: {
            type: Object,
            default: () => ({
                lng: 116.404,
                lat: 39.915
            })
        },
        initialZoom: {
            type: Number,
            default: 12
        },
        selectedLocation: {
            type: Object,
            default: () => ({
                lng: null,
                lat: null,
                address: ''
            })
        }
    },
    data() {
        return {
            dialogVisible: false,
            map: null,
            marker: null,
            geocoder: null,
            placeSearch: null,
            searchAddress: '',
            selectedPosition: null,
            selectedAddress: '',
            AMap: null
        }
    },
    watch: {
        visible(val) {
            this.dialogVisible = val
        },
        dialogVisible(val) {
            this.$emit('update:visible', val)
        }
    },
    methods: {
        async initMap() {
            if (!window.AMap) {
                // 设置安全密钥
                window._AMapSecurityConfig = {
                    securityJsCode: 'fe04608cc70ad1555c3f0a7474138966'
                }
                
                try {
                    this.AMap = await AMapLoader.load({
                        key: '861c2a8351746ee9c34616518ed20b84',
                        version: '2.0',
                        plugins: ['AMap.Geocoder', 'AMap.PlaceSearch']
                    })
                } catch (error) {
                    console.error('高德地图加载失败:', error)
                    this.$message.error('地图加载失败，请刷新页面重试')
                    return
                }
            }

            // 创建地图实例
            this.map = new this.AMap.Map('amap', {
                zoom: this.initialZoom,
                center: [
                    this.selectedLocation.lng || this.initialCenter.lng,
                    this.selectedLocation.lat || this.initialCenter.lat
                ]
            })

            // 初始化地理编码服务
            this.geocoder = new this.AMap.Geocoder()
            
            // 初始化搜索服务
            this.placeSearch = new this.AMap.PlaceSearch({
                map: this.map,
                pageSize: 10,
                pageIndex: 1,
                citylimit: true,
                autoFitView: true
            })

            // 如果有已选位置，显示标记
            if (this.selectedLocation.lng && this.selectedLocation.lat) {
                this.addMarker([this.selectedLocation.lng, this.selectedLocation.lat])
                this.selectedPosition = {
                    lng: this.selectedLocation.lng.toString(),
                    lat: this.selectedLocation.lat.toString()
                }
                this.selectedAddress = this.selectedLocation.address
            }

            // 点击地图获取位置
            this.map.on('click', (e) => {
                const lnglat = e.lnglat
                this.selectedPosition = {
                    lng: lnglat.getLng().toString(),
                    lat: lnglat.getLat().toString()
                }
                this.reverseGeocode([lnglat.getLng(), lnglat.getLat()])
                this.addMarker([lnglat.getLng(), lnglat.getLat()])
            })
        },

        handleDialogOpen() {
            this.$nextTick(() => {
                this.initMap()
            })
        },

        handleDialogClose() {
            if (this.map) {
                this.map.destroy()
                this.map = null
            }
            this.selectedPosition = null
            this.selectedAddress = ''
        },

        addMarker(position) {
            // 清除已有标记
            if (this.marker) {
                this.map.remove(this.marker)
            }
            // 添加新标记
            this.marker = new this.AMap.Marker({
                position: position,
                map: this.map
            })
        },

        searchLocation() {
            if (!this.searchAddress) return
            
            this.placeSearch.search(this.searchAddress, (status, result) => {
                if (status === 'complete' && result.info === 'OK') {
                    if (result.poiList && result.poiList.pois && result.poiList.pois.length > 0) {
                        const poi = result.poiList.pois[0]
                        const position = [poi.location.lng, poi.location.lat]
                        
                        this.map.setCenter(position)
                        this.selectedPosition = {
                            lng: position[0].toString(),
                            lat: position[1].toString()
                        }
                        this.selectedAddress = poi.address || poi.name
                        this.addMarker(position)
                    } else {
                        this.$message.warning('未找到相关地址')
                    }
                } else {
                    this.$message.error('搜索失败，请重试')
                }
            })
        },

        reverseGeocode(position) {
            this.geocoder.getAddress(position, (status, result) => {
                if (status === 'complete' && result.info === 'OK') {
                    this.selectedAddress = result.regeocode.formattedAddress
                }
            })
        },

        handleConfirm() {
            if (this.selectedPosition && this.selectedAddress) {
                this.$emit('confirm', {
                    address: this.selectedAddress,
                    longitude: Number(this.selectedPosition.lng),
                    latitude: Number(this.selectedPosition.lat)
                })
                this.dialogVisible = false
            } else {
                this.$message.warning('请先在地图上选择位置')
            }
        },

        handleCancel() {
            this.dialogVisible = false
        }
    }
}
</script>

<style scoped>
.map-container {
    width: 100%;
    height: 500px;
}

.map-search {
    margin-bottom: 10px;
}

.map-content {
    width: 100%;
    height: 450px;
    border: 1px solid #dcdfe6;
}

.selected-address {
    margin-top: 10px;
    padding: 10px;
    background-color: #f5f7fa;
    border-radius: 4px;
}

.address-info {
    display: flex;
    flex-direction: column;
    gap: 8px;
}

.info-item {
    display: flex;
    align-items: center;
}

.info-item .label {
    font-weight: bold;
    width: 60px;
    color: #606266;
}

.info-item .value {
    color: #303133;
}
</style> 